import React, { Component } from 'react'
import {
    Text,
    View,
    StyleSheet,
    Image,
    Dimensions,
    Platform,
    TouchableOpacity,
    KeyboardAvoidingView,
    ScrollView,
    AppState,
    PermissionsAndroid
} from 'react-native'
import NavBar from 'src/components/navBar'
import { scaleSize } from 'src/utils/ScreenUtils'
import DownloadUtil from 'src/utils/DownloadUtil'
import navigationhelper from 'src/components/navigationhelper'
import Auth from '../../../service/Auth'
import { inject } from "mobx-react/native"
import Layer from "src/components/Layer"
import * as WeChat from 'react-native-wechat';
import ActionSheet from 'react-native-actionsheet'
import ShareAlertView from '../components/shareAlertView'

const { width, height } = Dimensions.get('window')

@inject('userAuth')

export default class Share extends Component<{}> {

    // static navigationOptions = ({ navigation, screenProps }) => ({
    //     header: null,
    //     gesturesEnabled: true,
    //     tabBarVisible: true,
    //     tabBarIcon: (({ tintColor, focused }) => {
    //         return (
    //             <Image
    //                 source={!focused ? mine : mine_active}
    //                 style={{ resizeMode: 'stretch' }}
    //             />
    //         )
    //     }),
    //     tabBarLabel: '分享'
    // })

    constructor(props) {
        super(props)
        this.state = {
            dataList: [],
            selectedImage: '',
            selectedColor: ''
        }
    }

    componentWillUnmount () {
        AppState.removeEventListener('change',this._handleAppStateChange);

      }

      componentDidMount(){
       AppState.addEventListener('change', this._handleAppStateChange);
    }
    _handleAppStateChange=(nextAppState)=>{
        console.log(11111111);
        if(nextAppState=='active'){
            this.props.userAuth.fetchCurrentUserInfo({token:this.props.userAuth.token})
        }
        this.lastAppState = nextAppState;
     }

    // 分享到好友
    shareToFriend(picUrl) {
        WeChat.isWXAppInstalled().then((isInstalled) => {
            if (isInstalled) {
                WeChat.shareToSession({
                    type: 'imageUrl',
                    imageUrl: picUrl,
                    webpageUrl: picUrl,
                }).then((response) => {
                    // console.log(response);
                    // Layer.showMsg('分享成功');
                }).catch((error) => {
                    let errorCode = Number(error.code);
                    if (errorCode === -2) {
                        Layer.showMsg('分享已取消');
                    } else {
                        Layer.showMsg('分享失败');
                    }
                })
            } else {
                Layer.showMsg('请先安装微信')
            }
        });
    }

    // 分享到朋友圈
    shareToTimeline(picUrl) {
        WeChat.isWXAppInstalled().then((isInstalled) => {
            if (isInstalled) {
                WeChat.shareToTimeline({
                    type: 'imageUrl',
                    imageUrl: picUrl,
                    webpageUrl: picUrl,
                }).then((response) => {
                    // console.log(response);
                    // Layer.showMsg('分享成功');
                }).catch((error) => {
                    let errorCode = Number(error.code);
                    if (errorCode === -2) {
                        Layer.showMsg('分享已取消');
                    } else {
                        Layer.showMsg('分享失败');
                    }
                })
            } else {
                Layer.showMsg('请先安装微信')
            }
        });

    }


    async requestReadPermission() {
        try {
            //返回string类型
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                {
                    //第一次请求拒绝后提示用户你为什么要这个权限
                    'title': '我要读写权限',
                    'message': '没权限我不能工作，同意就好了'
                }
            )
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                DownloadUtil.saveImageAlbum(this.state.selectedImage)
            } else {

            }
        } catch (err) {

        }
    }



    componentDidMount = () => {
        this.getShareDatas()
    }

    getShareDatas = () => {
        Layer.showLoading()
        Auth.userShareImage({ token: this.props.userAuth.token }).then((res) => {
            Layer.hiddenLoading()
            if (res.status == 'success') {
                this.setState({
                    dataList: res.data,
                    selectedImage: res.data[0].path,
                    selectedColor: res.data[0].bg_color
                })
            }
        }).catch((res) => {
            Layer.hiddenLoading()
            Layer.showMsg(res.message)
        })
    }
    handleSelectImage = (dict) => {
        this.setState({
            selectedImage: dict.path,
            selectedColor: dict.bg_color,
        });
    }
    render() {
        const { dataList, selectedImage, selectedColor } = this.state
        return (
            <KeyboardAvoidingView
                style={{ flex: 1 }}
                behavior={Platform.OS === 'ios' ? 'padding' : 'none'}>
                <View
                    style={{
                        backgroundColor: selectedColor,
                        width: width,
                        height: height,
                        justifyContent: "center",
                        alignItems: 'center',
                        opacity: 0.4,
                        position: "absolute",
                    }}>
                </View>
                <NavBar
                    back={()=>{navigationhelper.goBack()}} 
                    title={'长按分享'}
                    leftText={'返回'} 
                    barStyle={'dark-content'}
                    />
                
                {/* <NavBar
                    title={<Text style={{ fontSize: 18, color:'#000' }}>长按分享</Text>}
                    backgroundColor={'transparent'}
                    statusBarBgColor={'#fff'}
                    barStyle={'light-content'}
                    hideLeftArrow={false}
                    // right={<Text style={{ fontSize: 16, color: '#fff', fontFamily: 'PingFang SC' }}>邀请记录</Text>}
                    // pressRight={() => navigationhelper.push('MyTeamUserManager')}
                /> */}
                <TouchableOpacity activeOpacity={1.0} delayLongPress={500} onLongPress={() => {
                    this.ActionSheet.show()
                }}>
                    <View style={{
                        width: width,
                        height: height,
                        justifyContent: "center",
                        alignItems: 'center',
                    }}>
                        <Image source={{ uri: selectedImage }} style={styles.bigImage} resizeMode={'contain'} />
                    </View>
                </TouchableOpacity>
                <View style={styles.smallImageContainer}>
                    <ScrollView horizontal={true}>
                        {
                            dataList.map((item, index) =>
                                <TouchableOpacity key={index} onPress={() => this.handleSelectImage(item)}>
                                    <View style={styles.smallImageItem}>
                                        <Image source={{ uri: item.path }} style={styles.smallImage} resizeMode={'cover'} />
                                    </View>
                                </TouchableOpacity>
                            )
                        }

                    </ScrollView>
                    <ShareAlertView
                        isVisible={false}
                        ref={i => this.regModal = i}
                        shareToTimeline={() => {
                            this.shareToTimeline(this.state.selectedImage)
                        }}
                        shareToFriend={() => {
                            this.shareToFriend(this.state.selectedImage)
                        }} />

                    <ActionSheet
                        ref={o => this.ActionSheet = o}
                        options={['保存图片', '分享二维码', '取消']}
                        cancelButtonIndex={2}
                        onPress={(index) => {
                            if (index === 0) {
                                if (Platform.OS == "android") {
                                    const granted = PermissionsAndroid.check(
                                        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
                                    )
                                    granted.then((data) => {
                                        if (data) {
                                            DownloadUtil.saveImageAlbum(selectedImage)
                                        } else {
                                            this.requestReadPermission()
                                        }

                                    })
                                }
                                else {
                                    DownloadUtil.saveImageAlbum(selectedImage)
                                }
                            } else if (index == 1) {
                                this.regModal.showOrDismiss(true)
                            }

                        }} />

                </View>

            </KeyboardAvoidingView>
        )
    }
}
const styles = StyleSheet.create({
    ground: {
        width: width,
        height: (730 * width) / 750
    },
    shadowAndroid: {
        width: width,
        flex: 1,
        backgroundColor: 'rgb(244,243,247)'
    },
    shadowIos: {
        width: width,
        height: 100,
        transform: [
            { translateY: -20 }
        ],
        backgroundColor: 'white',
        shadowColor: 'white',
        shadowOffset: {
            width: 0,
            height: -40
        },
        shadowOpacity: 1,
        shadowRadius: 20
    },
    willLogin: {
        alignSelf: "center",
        position: 'absolute',
        bottom: 20
    },
    edition: {
        color: 'gray',
        fontSize: 12,
    },
    bigImage: {
        width: scaleSize(400),
        height: scaleSize(700),
        marginBottom: scaleSize(500)
    },
    smallImageContainer: {
        width: width,
        height: 120,
        backgroundColor: 'rgba(255,255,255,0.4)',
        borderRadius: 20,
        borderBottomLeftRadius: 0,
        borderBottomRightRadius: 0,
        paddingLeft: 20,
        paddingRight: 20,
        paddingTop: 10,
        paddingBottom: 10,
        justifyContent: "center",
        flexDirection: "row",
        position: 'absolute',
        bottom: 0
    },
    smallImageItem: {
        width: 50,
        height: 100,
        marginLeft: 15,
    },
    smallImage: {
        width: 50,
        height: 100,
        borderRadius: 5,
    }

})